package com.nativetalk.service.three.reserve.insert;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.TdNtSystemMessage;
import com.nativetalk.bean.course.TsNtCourseInfoDetail;
import com.nativetalk.bean.course.TwoTsNtCourseInfoDetail;
import com.nativetalk.bean.live.TdNtLiveCourseHisDetail;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.reserve.TdNtReserveInsert;
import com.nativetalk.bean.setmeal.TsNtSetmealIndex;
import com.nativetalk.bean.teacher.TdNtTeacherCourse;
import com.nativetalk.bean.teacher.TdNtTeacherTuisong;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidReserveTeacher;
import com.nativetalk.common.getui.IosReserveTeacher;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 16/6/15.
 */
@Service
public class ThreeReserveInsertServiceImpl implements ThreeReserveInsertService{
    private static Logger logger = Logger.getLogger(ThreeReserveInsertServiceImpl.class);
    @Resource
    private TdNtReserveDao tdNtReserveDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtLiveCourseHisDao tdNtLiveCourseHisDao;
    @Resource
    private TdNtSystemMessageDao tdNtSystemMessageDao;
    @Override
    @Transactional
    public synchronized RetInfo addTdNtReserveInsert(TdNtReserveInsert tdNtReserveInsert, int version, int type, TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":addTdNtReserveInsert:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            /**
             * 查找该老师是否有冲突时间的直播
             */
            Map<String, Object> map = new HashMap<>();
            map.put("tea_id",tdNtReserveInsert.getReserve_start_time());
            map.put("start_time",tdNtReserveInsert.getReserve_start_time());
            map.put("end_time",tdNtReserveInsert.getReserve_end_time());
            TdNtReserveInsert tdNtReserve = tdNtReserveDao.findTdNtReserverConflict(map);
            if (tdNtReserve != null) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("该老师该时间已被预约,请预约其他时间");
                return  retInfo;
            } else {
                TdNtLiveCourseHisDetail live = tdNtLiveCourseHisDao.findTdNtLiveCourseHisDetailConflict(map);
                if (live != null) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("该老师该时间已被预约,请预约其他时间");
                    return  retInfo;
                }
            }
            // 是否是体验预约老师 0 是 ，1 否
            if (type == 0){
                TdNtReserveInsert tdNtReserver = tdNtReserveDao.findTdNtReserver(tdNtReserveInsert.getMemb_id());
                if (tdNtReserver != null){
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("已体验过!");
                } else {
                    tdNtReserveInsert.setReserve_time(15);
                    tdNtReserveInsert.setAmout(new BigDecimal(0));
                    tdNtReserveInsert.setState(Constants.ReserveState.ready_to_begin);
                    tdNtReserveDao.insertTdNtReserve(tdNtReserveInsert);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("成功");
                }

            } else {
                if (version >= 8) {
                    tdNtReserveInsert.setReserve_time(30);
                } else {
                    tdNtReserveInsert.setReserve_time(60);
                }
                BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtReserveInsert.getMemb_id());
                BigDecimal reserve_amount;
                //判断是否为自由话题
                if (tdNtReserveInsert.getCou_id() == 100) {
                    TdNtTeacherCourse tdNtTeacherCourse = tdNtTeacherDao.findTeacherStudy(tdNtReserveInsert.getTea_id());
                    reserve_amount = tdNtTeacherCourse.getMin_amount().multiply(new BigDecimal(tdNtReserveInsert.getReserve_time()));
                } else {
                    Map<String,TwoTsNtCourseInfoDetail> tsNtCourseInfoDetailMapTwo  = (Map<String, TwoTsNtCourseInfoDetail>) MemcachedUtils.get(MemcachedKey.tsNtCourseInfoDetailMapTwo);
                    Map<String, TsNtSetmealIndex> tsNtSetmealSynopisMap = (Map<String, TsNtSetmealIndex>) MemcachedUtils.get(MemcachedKey.tsNtSetmealIndexMap);
                    String cate_id = tsNtCourseInfoDetailMapTwo.get(tdNtReserveInsert.getCou_id() + "").getCate_id().toString();
                    TsNtSetmealIndex setmealIndex = tsNtSetmealSynopisMap.get(cate_id);
                    reserve_amount = setmealIndex.getSet_amout().divide(
                            new BigDecimal(setmealIndex.getSet_time()),2, BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(tdNtReserveInsert.getReserve_time()));
                }
                //判断余额是否足够
                if (memb_balance.compareTo(reserve_amount) > -1) {
                    tdNtReserveInsert.setAmout(reserve_amount);
                    tdNtReserveInsert.setState(Constants.ReserveState.ready_to_begin);

                    memb_balance = memb_balance.subtract(reserve_amount);
                    TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                    tdNtMemberInvite.setMemb_balance(memb_balance);
                    tdNtMemberInvite.setMemb_id(tdNtReserveInsert.getMemb_id());
                    /**
                     * 添加资金变动记录
                     */
                    TdNtMembFoundChangeInset tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                    tdNtMembFoundChangeInset.setMemb_id(tdNtReserveInsert.getMemb_id());
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(new Date()));
                    tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance);
                    tdNtMembFoundChangeInset.setMfchg_change_amount(reserve_amount);
                    tdNtMembFoundChangeInset.setMfchg_change_name("购买课程");
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                    tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance.add(reserve_amount));
                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                    tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());

                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);
                    tdNtReserveDao.insertTdNtReserve(tdNtReserveInsert);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("成功");
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MEMBBALANCE.NO"));
                    return  retInfo;
                }
            }

            /**
             * todo 给教师发推送及邮件
             */
            TdNtTeacherTuisong tdNtTeacherTuisong = tdNtTeacherDao.findTdNtTeacherTuisong(tdNtReserveInsert.getTea_id());
            if (tdNtTeacherTuisong.getEqu_client_id() != null && !(tdNtTeacherTuisong.getEqu_client_id().equals(Constants.default_equ_id))) {
                /**
                 * 发推送
                 */
                if (tdNtTeacherTuisong.getEqu_type().equals("1")) {
                    AndroidReserveTeacher.apnpush("NativeTalk","Dear NativeTalk tutor, new assignment class, please check and arrange some time for the class.\n ",
                            tdNtTeacherTuisong.getEqu_client_id(),tdNtReserveInsert.getReserve_id());
                } else {
                    logger.info(tdNtTeacherTuisong.getEqu_client_id());
                    IosReserveTeacher.apnpush("NativeTalk","Dear NativeTalk tutor, new assignment class, please check and arrange some time for the class.\n ",
                            tdNtTeacherTuisong.getEqu_client_id(),tdNtReserveInsert.getReserve_id());

                }
                // 处理html邮件模板
                //教学费用 老师每分钟0.2美分
                //从缓存中读取老师每分钟的教学费用
                Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
                //教学费用 老师每分钟0.2美分
                BigDecimal tea_amount = new BigDecimal(tsNtWebSiteConfIndexMap.get("24").getData_value());//0.2
                int courseDuration = tdNtReserveInsert.getReserve_time();//预约的课程的上课时长
                BigDecimal earnMoney = tea_amount.multiply(new BigDecimal(courseDuration));//老师上完课应该赚取多少钱 = 每分钟单价 X 课程的时长（分钟）

                Map<String, TsNtCourseInfoDetail> courseMap = (Map<String, TsNtCourseInfoDetail>) MemcachedUtils.get(MemcachedKey.tsNtCourseInfoDetailMap);
                int cou_id = tdNtReserveInsert.getCou_id();
                TsNtCourseInfoDetail course = courseMap.get(cou_id + "");

                // freemarker的model(数据模型)
                Map<String, Object> ftlModel = new HashedMap();
                ftlModel.put("tea_name", tdNtTeacherTuisong.getTea_name());
                ftlModel.put("memb_name", tdNtMember.getMemb_name());
                ftlModel.put("course_name", course.getCou_english_name());
                ftlModel.put("start_time", DateUtil.format(tdNtReserveInsert.getReserve_end_time(), "MM-DD HH:mm"));
                ftlModel.put("money", earnMoney.doubleValue());

                // freemarker 初始化
                Configuration cfg = Configuration.getDefaultConfiguration();
                String path = this.getClass().getResource("/").getPath() + "email/";
                cfg.setDirectoryForTemplateLoading(new File(path));
                cfg.setDefaultEncoding("utf-8");
                Template temp = cfg.getTemplate("teacher_course_notify.ftl", "UTF-8");
                StringWriter stringWriter = new StringWriter();
                BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
                temp.process(ftlModel, stringWriter);

                String toEmail = tdNtTeacherTuisong.getTea_email();//收件人邮箱
                String subject = "[NativeTalk] New Appointment";//邮件标题
                String htmlContent = stringWriter.toString();//邮件内容

                SendMailUtil.sendMail(toEmail, subject, htmlContent);// 发送邮件

            }



        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
